/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pig4cloud.pig.common.core.util;

import com.pig4cloud.pig.common.core.constant.CommonConstants;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.experimental.FieldNameConstants;

import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @param <T> 响应数据的泛型类型
 * @author lengleng
 */
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@FieldNameConstants
public class R<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * 响应码
	 */
	@Getter
	@Setter
	private int code;

	/**
	 * 响应消息
	 */
	@Getter
	@Setter
	private String msg;

	/**
	 * 响应数据
	 */
	@Getter
	@Setter
	private T data;

	/**
	 * 返回成功响应（无数据）
	 * @param <T> 泛型类型
	 * @return 成功响应对象
	 */
	public static <T> R<T> ok() {
		return restResult(null, CommonConstants.SUCCESS, null);
	}

	/**
	 * 返回成功响应（带数据）
	 * @param data 响应数据
	 * @param <T> 泛型类型
	 * @return 成功响应对象
	 */
	public static <T> R<T> ok(T data) {
		return restResult(data, CommonConstants.SUCCESS, null);
	}

	/**
	 * 返回成功响应（带数据和消息）
	 * @param data 响应数据
	 * @param msg 响应消息
	 * @param <T> 泛型类型
	 * @return 成功响应对象
	 */
	public static <T> R<T> ok(T data, String msg) {
		return restResult(data, CommonConstants.SUCCESS, msg);
	}

	/**
	 * 返回失败响应（无数据）
	 * @param <T> 泛型类型
	 * @return 失败响应对象
	 */
	public static <T> R<T> failed() {
		return restResult(null, CommonConstants.FAIL, null);
	}

	/**
	 * 返回失败响应（带消息）
	 * @param msg 失败消息
	 * @param <T> 泛型类型
	 * @return 失败响应对象
	 */
	public static <T> R<T> failed(String msg) {
		return restResult(null, CommonConstants.FAIL, msg);
	}

	/**
	 * 返回失败响应（带数据）
	 * @param data 响应数据
	 * @param <T> 泛型类型
	 * @return 失败响应对象
	 */
	public static <T> R<T> failed(T data) {
		return restResult(data, CommonConstants.FAIL, null);
	}

	/**
	 * 返回失败响应（带数据和消息）
	 * @param data 响应数据
	 * @param msg 失败消息
	 * @param <T> 泛型类型
	 * @return 失败响应对象
	 */
	public static <T> R<T> failed(T data, String msg) {
		return restResult(data, CommonConstants.FAIL, msg);
	}

	/**
	 * 构建响应结果
	 * @param data 响应数据
	 * @param code 响应码
	 * @param msg 响应消息
	 * @param <T> 泛型类型
	 * @return 响应对象
	 */
	public static <T> R<T> restResult(T data, int code, String msg) {
		R<T> apiResult = new R<>();
		apiResult.setCode(code);
		apiResult.setData(data);
		apiResult.setMsg(msg);
		return apiResult;
	}

}
